import React from "react";
import { Table } from "antd";
import styles from "./index.module.less";
import { isObject } from "lodash-es";
function createElNode(tagName = "div") {
  return document.createElement(tagName) as any;
}
function getTextWidth(text: any, fontSize: any = 14) {
  const _span = createElNode("span");
  _span.innerText = text;
  _span.style.fontSize = parseInt(fontSize) + "px";
  _span.style.position = "absolute";
  document.body.appendChild(_span);
  let width = _span.offsetWidth;
  document.body.removeChild(_span);
  return width;
}
const BasicTable: React.FC<any> = (props: any) => {
  const {
    columns,
    scroll = { x: "max-content" },
    sticky = true,
    className = styles["basic-table"],
    dataSource = [],
    tablePage,
    rowKey = (record: { diff_key: any }) => record.diff_key,
    bordered = true,
    ...args
  } = props;

  columns.forEach((column: any) => {
    column.align ??= "center";
    const render = column.render;
    column.render = (text: any, record: any, index: any) => (
      <div
        className={styles.center}
        style={{
          minWidth: getTextWidth(column.title) + "px",
        }}
      >
        {render ? render(text, record, index) : text}
      </div>
    );
    if (column.key === "action") column.fixed ??= "right";
  });

  const $props = {
    columns,
    scroll,
    sticky,
    className,
    dataSource,
    pagination: isObject(tablePage)
      ? {
          showQuickJumper: true,
          showLessItems: true,
          showTotal: (total: any) => `共计 ${total} 条`,
          ...tablePage,
        }
      : false,
    rowKey,
    bordered,
    ...args,
  };
  return <Table {...$props} />;
};

export default BasicTable;
